package com.aiti.lulian.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.utils.encrypt.Md5Util;
import com.aiti.base.core.utils.message.Message;
import com.aiti.base.core.utils.uuid.UUIDUtil;
import com.aiti.lulian.constant.GxmhConstant;
import com.aiti.lulian.dto.ShowEnterpriseServiceDto;
import com.aiti.lulian.entity.ShowEnterpriseServiceEntity;
import com.aiti.lulian.entity.ShowServiceEnterprise;
import com.aiti.lulian.entity.excel.ShowEnterpriseServiceEntityImport;
import com.aiti.lulian.gxmh.dto.SubUser;
import com.aiti.lulian.gxmh.dto.SysUserDto;
import com.aiti.lulian.gxmh.entity.GxmhServerServices;
import com.aiti.lulian.gxmh.service.GxmhServerServicesService;
import com.aiti.lulian.mapper.ShowEnterpriseServiceMapper;
import com.aiti.lulian.mapper.ShowServiceEnterpriseMapper;
import com.aiti.lulian.mapper.gxmh.GxmhSysMapper;
import com.aiti.lulian.service.IShowEnterpriseServiceService;
import com.aiti.lulian.vo.ShowEnterpriseServiceVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务 服务实现类
 * </p>
 *
 * @author 
 * @since 2025-06-11
 */
@Service
public class ShowEnterpriseServiceServiceImpl extends ServiceImpl<ShowEnterpriseServiceMapper, ShowEnterpriseServiceEntity> implements IShowEnterpriseServiceService {

    @Autowired
    private ShowServiceEnterpriseMapper serviceEnterpriseMapper;
    @Autowired
    private GxmhServerServicesService gxmhServerServicesService;
    @Autowired
    private GxmhSysMapper gxmhSysMapper;

    @Override
    public List<ShowEnterpriseServiceVo> serviceList(Page page, ShowEnterpriseServiceDto dto) {
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(dto.getUserId());
        if(sysUserDto == null) {
            throw new BusinessException("用户不存在");
        }
        if(GxmhConstant.GXMH_SERVER_USER_FLAG.equals(sysUserDto.getSource())) {
            return this.baseMapper.serverServicePage(page, dto);
        }
        return this.getBaseMapper().servicePage(page, dto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addServerUser(ShowEnterpriseServiceEntity dto, ShowServiceEnterprise serviceEnterprise, String loginUserId) {
        if(StrUtil.isNotBlank(dto.getIsCreateServiceUser()) && "1".equals(dto.getIsCreateServiceUser())) {
            SubUser subUser = this.createServerUser(dto, serviceEnterprise);
            GxmhServerServices gxmhServerServices= this.getGxmhServerServices(dto, subUser, loginUserId);
            gxmhServerServicesService.save(gxmhServerServices);
        }
    }

    private GxmhServerServices getGxmhServerServices(ShowEnterpriseServiceEntity dto, SubUser subUser, String loginUserId) {
        GxmhServerServices gxmhServerServices = new GxmhServerServices();
        gxmhServerServices.setBaseId(UUIDUtil.getUUID2());
        gxmhServerServices.setUserId(subUser.getBaseId());
        gxmhServerServices.setServiceId(dto.getBaseId());
        gxmhServerServices.setBaseCreateBy(loginUserId);
        gxmhServerServices.setBaseCreateTime(new Date());
        gxmhServerServices.setBaseUpdateBy(loginUserId);
        gxmhServerServices.setBaseUpdateTime(new Date());
        gxmhServerServices.setIsDelete(0);
        return gxmhServerServices;
    }

    /**
     * 创建产品服务商用户
     * @param dto
     */
    private SubUser createServerUser(ShowEnterpriseServiceEntity dto, ShowServiceEnterprise serviceEnterprise) {
        if(StrUtil.isBlank(dto.getUsername()) && StrUtil.isBlank(dto.getPassword())) {
            throw new BusinessException("请填写用户名和密码");
        }
        // 判断用户是否存在
        String existUserId = gxmhSysMapper.queryUserIdByUsername(dto.getUsername());
        if(StrUtil.isNotEmpty(existUserId)) {
            throw new BusinessException("用户【"+dto.getUsername()+"】已存在，请联系管理员处理");
        }
        // 创建用户和角色绑定
        SubUser subUser = buildSubUser(dto, serviceEnterprise);
        gxmhSysMapper.insertServerUser(subUser);
        gxmhSysMapper.insertUserRole(UUIDUtil.getUUID2(), subUser.getBaseId(), GxmhConstant.SERVICE_SERVER_ROLE_ID);
        return subUser;
    }

    private SubUser buildSubUser(ShowEnterpriseServiceEntity dto, ShowServiceEnterprise serviceEnterprise) {
        String username = dto.getUsername();
        String password = dto.getPassword();

        SubUser subUser = new SubUser();
        subUser.setBaseId(UUIDUtil.getUUID2());
        subUser.setUsername(username);
        subUser.setMobile(username);
        subUser.setIsMain(true);
        subUser.setIsSignin("1");
        subUser.setIsDelete(false);
        subUser.setSource(GxmhConstant.GXMH_SERVER_USER_FLAG);
        subUser.setBaseCreateTime(new Date());
        subUser.setBaseUpdateTime(new Date());
        subUser.setProvince(GxmhConstant.SHAN_DONG_PROVINCE);
        subUser.setCity(serviceEnterprise.getCity());
        subUser.setRegion(serviceEnterprise.getCounty());
        subUser.setStreet(serviceEnterprise.getStreet());
        subUser.setBackgroundId("a5ed9caf3b1960e6b3b43bb6c1ffbddc");
        subUser.setSelectedTemplateId("a5ed9caf3b1960e6b3b43bb6c1ffbddc");
        subUser.setYmm(StrUtil.isNotBlank(subUser.getPassword()) ? password : username);
        String password1 = Md5Util.hash(password);
        subUser.setPassword(password1);
        return subUser;
    }
    @Override
    public void setDetailInfo(ShowEnterpriseServiceEntity entity, String loginUserId){
        LambdaQueryWrapper<GxmhServerServices> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GxmhServerServices::getServiceId, entity.getBaseId()).eq(GxmhServerServices::getIsDelete, 0);
        GxmhServerServices serverServices = gxmhServerServicesService.getOne(queryWrapper);
        if(serverServices != null) {
            SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(serverServices.getUserId());
            entity.setServerUsername(sysUserDto.getUsername());
            entity.setServerUserExistFlag(true);
            if(loginUserId.equals(serverServices.getBaseCreateBy())) {
                entity.setDelServerUserFlag(1);
            }
        }
    }


    @Override
    public void removeServerUser(String serviceId) {
        LambdaQueryWrapper<GxmhServerServices> queryWrapper = new LambdaQueryWrapper<GxmhServerServices>().eq(GxmhServerServices::getServiceId, serviceId).eq(GxmhServerServices::getIsDelete, 0);
        List<GxmhServerServices> list = gxmhServerServicesService.list(queryWrapper);
        if(CollectionUtil.isNotEmpty(list) ) {
            for (GxmhServerServices gxmhServerServices : list) {
                String userId = gxmhServerServices.getUserId();
                gxmhSysMapper.deleteUserRoleByUserId(userId);
                gxmhSysMapper.deleteUserByUserId(userId);
            }
            gxmhServerServicesService.remove(queryWrapper);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteServerUser(String username, String serviceId) {
        String userId = gxmhSysMapper.queryUserIdByUsername(username);
        if(StrUtil.isNotEmpty(userId)) {
            // 删除用户角色和用户数据
            gxmhSysMapper.deleteUserRoleByUserId(userId);
            gxmhSysMapper.deleteUserByUsername(username);
        }
        LambdaQueryWrapper<GxmhServerServices> queryWrapper = new LambdaQueryWrapper<GxmhServerServices>()
                .eq(GxmhServerServices::getServiceId, serviceId)
                .eq(GxmhServerServices::getUserId, userId)
                .eq(GxmhServerServices::getIsDelete, 0);

        // 删除绑定数据
        gxmhServerServicesService.remove(queryWrapper);
    }

    @Override
    public Message addCount(ShowEnterpriseServiceDto dto) {

        String baseId = dto.getBaseId();
        if(StrUtil.isNotBlank(baseId)){
            LambdaUpdateWrapper<ShowEnterpriseServiceEntity> wrapper =
                    new LambdaUpdateWrapper<>();
            wrapper.eq(ShowEnterpriseServiceEntity::getBaseId, baseId)
                    .setSql("click_count = click_count + 1");
            this.update(null, wrapper);
            return Message.success();
        }else{
            return Message.fail("传参有误，缺少传参");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message importBatch(MultipartFile file, String userId) throws IOException {
        // 构建报错信息集
        List<String> msgList = new ArrayList<>();
        // 读取数据
        List<ShowEnterpriseServiceEntityImport> enterpriseServiceImportList = EasyExcel.read(file.getInputStream()).head(ShowEnterpriseServiceEntityImport.class).headRowNumber(1).sheet("服务").doReadSync();
        if (enterpriseServiceImportList == null) {
            return Message.fail("请正确上传文件");
        }
        if (enterpriseServiceImportList != null && enterpriseServiceImportList.size() == 0) {
            return Message.fail("尚未读取到数据");
        }
        List<ShowEnterpriseServiceEntity> enterpriseServices = new ArrayList<>();
        for (ShowEnterpriseServiceEntityImport enterpriseServiceImport : enterpriseServiceImportList) {
            if (StrUtil.isBlank(enterpriseServiceImport.getEnterpriseName())) {
                msgList.add("第" + (enterpriseServiceImportList.indexOf(enterpriseServiceImport) + 1) + "条：公司名称不能为空<br/>");
                continue;
            }
            if (StrUtil.isBlank(enterpriseServiceImport.getBaseName())) {
                msgList.add("第" + (enterpriseServiceImportList.indexOf(enterpriseServiceImport) + 1) + "条：服务项目不能为空<br/>");
                continue;
            }
            if (StrUtil.isBlank(enterpriseServiceImport.getServiceType())) {
                msgList.add("第" + (enterpriseServiceImportList.indexOf(enterpriseServiceImport) + 1) + "条：服务类型不能为空<br/>");
                continue;
            }
            if (StrUtil.isBlank(enterpriseServiceImport.getDescription())) {
                msgList.add("第" + (enterpriseServiceImportList.indexOf(enterpriseServiceImport) + 1) + "条：服务说明不能为空<br/>");
                continue;
            }
            ShowServiceEnterprise serviceEnterprise = serviceEnterpriseMapper.selectOne(new LambdaQueryWrapper<ShowServiceEnterprise>().eq(ShowServiceEnterprise::getBaseName, enterpriseServiceImport.getBaseName()).eq(ShowServiceEnterprise::getIsDelete, false));
            if (serviceEnterprise == null) {
                msgList.add("第" + (enterpriseServiceImportList.indexOf(enterpriseServiceImport) + 1) + "条：公司尚未查询到<br/>");
            } else {
                ShowEnterpriseServiceEntity enterpriseService = new ShowEnterpriseServiceEntity();
                enterpriseService.setBaseName(enterpriseServiceImport.getBaseName());
                enterpriseService.setServiceType(enterpriseServiceImport.getServiceType());
                enterpriseService.setDescription(enterpriseServiceImport.getDescription());
                enterpriseService.setEnterpriseId(serviceEnterprise.getBaseId());
                enterpriseService.setEnterpriseName(serviceEnterprise.getBaseName());
                enterpriseService.setProvince(serviceEnterprise.getProvince());
                enterpriseService.setCity(serviceEnterprise.getCity());
                enterpriseService.setCounty(serviceEnterprise.getCounty());
                enterpriseService.setTelephone(serviceEnterprise.getTelephone());
                enterpriseService.setLogo(serviceEnterprise.getLogo());
                enterpriseService.setAddress(serviceEnterprise.getAddress());
                enterpriseService.setCreator(userId);
                enterpriseService.setBaseCreateTime(new Date());
                enterpriseServices.add(enterpriseService);
            }
        }
        if (enterpriseServices.size() > 0) {
            this.saveBatch(enterpriseServices);
        }
        if (msgList.size() > 0) {
            return Message.fail("以下数据导入失败：<br/>" + msgList.stream().collect(Collectors.joining("")));
        } else {
            return Message.success("导入成功");
        }
    }
}
